package org.bt4girls.common.utils;


import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.bt4girls.common.constant.CommonConstant;

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

public class PasswordUtils {

    /***
     * 用户密码加密
     * @param arg 字符串
     * @return String 加密后字符串
     */
    public static String encryptUserPwd(String arg) {
        //base64(salt.md5(pwd+key+salt)) 长度计算 16(salt) + .(1) + md5(32)
        String salt = RandomUtils.generateRandomString(16);
        String tmp = DigestUtils.md5Hex(arg + CommonConstant.PWD_KEY_STR + salt);
        return salt + "." + tmp;
    }

    /***
     * 密码校验
     * @param original 原文
     * @param cipher 密文
     * @return boolean 是否验证成功
     */
    public static boolean checkUserPwd(String original, String cipher) {
        if (StringUtils.isBlank(original) || StringUtils.isBlank(cipher)) {
            return false;
        }
        String[] arr = cipher.split("\\.");
        if (arr.length != 2) return false;
        String salt = arr[0];
        String pwd = salt + "." + DigestUtils.md5Hex(original + CommonConstant.PWD_KEY_STR + salt);
        return cipher.equals(pwd);
    }


}
